package com.zhenyi.tuangou.task;

import java.util.Date;
import java.util.List;

import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.zhenyi.common.model.TgGroup;
import com.zhenyi.tuangou.core.WXPayUtils;
import com.zhenyi.tuangou.index.OrderSingleton;

public class CloseGroupTask implements Runnable {

	/**
	 * 时间到结束时间关闭团购
	 */
	@Override
	public void run() {
		OrderSingleton orderSingleto = OrderSingleton.getintsance();
		if (orderSingleto.isOn()) {
			return;
		}
		orderSingleto.turnOff();
		SqlPara sqlPara = Db.getSqlPara("findGroupByStatus");
		List<Record> items = Db.find(sqlPara);
		if (items == null) {
			return;
		}
		for (Record record : items) {
			TgGroup tgGroup = TgGroup.dao.findById(record.getLong("id"));
			Date endTime = tgGroup.getEndTime();
			Date nowTime = new Date();
			long diff = nowTime.getTime() - endTime.getTime();
			if (diff < 0) {
				continue;
			}
			tgGroup.setStatus(TgGroup.STATUS_CLOSE);// 关闭团购
			tgGroup.update();
			openGroupFail(tgGroup);
			orderSingleto.turnOn();
			if (tgGroup.getJoinLeft() > 0) {
				continue;
			}
			if (tgGroup.getJoinLeft() < 0) {
				LogKit.warn("参团人数出错 " + tgGroup.getId());
				continue;
			}
			tgGroup.setStatus(TgGroup.STATUS_SUCCESS);// 团购成功(人数已购)
			tgGroup.update();
		}
	}

	/**
	 * 参团失败,退钱
	 * 
	 * @param tgGroup
	 */
	public void openGroupFail(TgGroup tgGroup) {
		Long id = tgGroup.getId();
		Kv cond = Kv.by("groupId", id);
		SqlPara sqlPara = Db.getSqlPara("findOrderById", cond);
		List<Record> list = Db.find(sqlPara);
		if (list == null && list.size() == 0) {
			LogKit.warn("退款名单出错: " + tgGroup.getId());
			return;
		}
		WXPayUtils wxPayUtils = new WXPayUtils();
		for (Record record : list) {
			String outTradeNo = record.getStr("outTradeNo");
			int paid = record.getInt("paid");
			wxPayUtils.refund(outTradeNo, paid);
		}
	}

}
